package com.panopset.flywheel;

import static com.panopset.Util.*;

import java.io.StringWriter;

import com.panopset.ReflectionInvoker;

/**
 * <h5>e - Execute</h5>
  <p>
  Excecute any public static method, which returns a String and takes 0 or
  more String parameters. If parameters match variable names, then
  they will be replaced by the variable value, otherwise the parameter will
  be used as is.
  </p>
  <p>
    You may register objects that will be available using the Flywheel.Builder.registerObject function.
    The keys must be one word.
  </p>
 *
 * <pre>
 *
 * ${&#064;p name}panopset${&#064;q}
 *
 * ${&#064;e com.panopset.Util.capitalize(name)}
 *
 * </pre>
 *
 * The above script will output:
 *
 * <pre>
 *
 * Panopset
 *
 * </pre>
 *
 * @author Karl Dinwiddie
 */
public class CommandExecute extends TemplateDirectiveCommand {

    public static String getShortHTMLText() {
        return "${&#064;e com.panopset.Util.capitalize(name)}";
    }

    public CommandExecute(String source, String innerPiece, Template template) {
        super(source, innerPiece, template);
    }

    @Override
    public void resolve(StringWriter sw) {
        try {
            String s = getParams();
            int i = s.lastIndexOf(".");
            if (i > -1) {
                String key = s.substring(0,i);
                Object object = template.flywheel.registeredObjects.get(key);
                if (object != null) {
                    sw.append(new ReflectionInvoker.Builder()
                    .object(object)
                    .methodAndParms(s.substring(i+1))
                    .mapProvider(template.flywheel).construct().exec());
                    return;
                }
            }
            sw.append(new ReflectionInvoker.Builder()
            .classMethodAndParms(
                    getParams()).mapProvider(template.flywheel).construct().exec());
        } catch (Exception e) {
            if (template != null) {
                log(template.getRelativePath());
                if (template.commandFile != null) {
                    log("Output file: " + template.commandFile);
                    log("source: " + source);
                }
            }
            log(e);
            template.flywheel.stop(e.getMessage());
        }
    }

}
